package com.ruoyi.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.system.domain.RecKjPaperManagementD;
import com.ruoyi.system.mapper.RecKjPaperManagementDMapper;
import com.ruoyi.system.service.IRecKjPaperManagementDService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.validation.Validator;
import java.util.List;
import java.util.Map;

/**
 * 专门档案  独立的Service业务层处理
 *
 * @author yzf
 * @date 2022-06-03
 */
@Service
public class RecKjPaperManagementDServiceImpl implements IRecKjPaperManagementDService {
    @Autowired
    protected Validator validator;
    private Logger log = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private RecKjPaperManagementDMapper recKjPaperManagementDMapper;

    @Override
    @Transactional
    public String importFile(List<RecKjPaperManagementD> fileList, String operName) {
        // 设置回滚点
        Object savePoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint();
        if (CollUtil.isEmpty(fileList)) {
            throw new ServiceException("导入文件数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (RecKjPaperManagementD file : fileList) {
            try {
                BeanValidators.validateWithException(validator, file);
                file.setCreateBy(operName);
                this.insertRecKjPaperManagementD(file);
                successNum++;
                successMsg.append("<br/>" + successNum + "、文件 " + file.getFileTitle() + " 导入成功");
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、文件 " + file.getFileTitle() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
                //手工回滚异常
                TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            //手工回滚异常
            TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 查询专门档案  独立的
     *
     * @param id 专门档案  独立的主键
     * @return 专门档案  独立的
     */
    @Override
    public RecKjPaperManagementD selectRecKjPaperManagementDById(String id) {
        return recKjPaperManagementDMapper.selectRecKjPaperManagementDById(id);
    }

    @Override
    public List<Map<String, Object>> selectlistByName(RecKjPaperManagementD recKjPaperManagementD) {
        return recKjPaperManagementDMapper.selectlistByName(recKjPaperManagementD);
    }

    /**
     * 查询专门档案  独立的列表
     *
     * @param recKjPaperManagementD 专门档案  独立的
     * @return 专门档案  独立的
     */
    @Override
    public List<RecKjPaperManagementD> selectRecKjPaperManagementDList(RecKjPaperManagementD recKjPaperManagementD) {
        return recKjPaperManagementDMapper.selectRecKjPaperManagementDList(recKjPaperManagementD);
    }

    /**
     * 新增专门档案  独立的
     *
     * @param recKjPaperManagementD 专门档案  独立的
     * @return 结果
     */
    @Override
    public int insertRecKjPaperManagementD(RecKjPaperManagementD recKjPaperManagementD) {

        //档案号生成   全宗号-档案类别-年度-件号
        //全宗号
        String fullAncestor = recKjPaperManagementD.getFullAncestor();
        if (StrUtil.isEmpty(fullAncestor)) {
            fullAncestor = "27";
        }
        //档案类别
        String fileCategory = recKjPaperManagementD.getFileCategory();
        if (StrUtil.isEmpty(fileCategory)) {
            throw new GlobalException("档案类别不能空,请按规则填写");
        }
        //年度
        String year = recKjPaperManagementD.getYear();
        if (StrUtil.isEmpty(year)) {
            throw new GlobalException("年度不能空,请按规则填写");
        }
        //件号
        String partNumber = recKjPaperManagementD.getPartNumber();
        recKjPaperManagementD.setFileNumber(getFileNumber(fullAncestor, fileCategory, year, partNumber));
        recKjPaperManagementD.setCreateTime(DateUtils.getNowDate());
        recKjPaperManagementD.setCreateBy(SecurityUtils.getUsername());
        return recKjPaperManagementDMapper.insertRecKjPaperManagementD(recKjPaperManagementD);
    }

    private String getFileNumber(String fullAncestor, String fileCategory, String year, String partNumber) {
        StringBuilder stb = new StringBuilder();
        stb.append(fullAncestor).append("-");
        stb.append(fileCategory).append("-");
        stb.append(year).append("-");
        stb.append(partNumber);
        return stb.toString();
    }

    /**
     * 修改专门档案  独立的
     *
     * @param recKjPaperManagementD 专门档案  独立的
     * @return 结果
     */
    @Override
    public int updateRecKjPaperManagementD(RecKjPaperManagementD recKjPaperManagementD) {
        recKjPaperManagementD.setUpdateTime(DateUtils.getNowDate());
        recKjPaperManagementD.setUpdateBy(SecurityUtils.getUsername());
        return recKjPaperManagementDMapper.updateRecKjPaperManagementD(recKjPaperManagementD);
    }

    /**
     * 批量删除专门档案  独立的
     *
     * @param ids 需要删除的专门档案  独立的主键
     * @return 结果
     */
    @Override
    public int deleteRecKjPaperManagementDByIds(String[] ids) {
        return recKjPaperManagementDMapper.deleteRecKjPaperManagementDByIds(ids);
    }

    /**
     * 删除专门档案  独立的信息
     *
     * @param id 专门档案  独立的主键
     * @return 结果
     */
    @Override
    public int deleteRecKjPaperManagementDById(String id) {
        return recKjPaperManagementDMapper.deleteRecKjPaperManagementDById(id);
    }

    @Override
    @Transactional
    public int updateArchivesApplyByIds(String[] Ids) {
        // 设置回滚点
        Object savePoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint();
        for (String id : Ids) {
            RecKjPaperManagementD recordArchives = new RecKjPaperManagementD();
            recordArchives.setId(id);
            recordArchives.setObjStr1("1"); //申请状态字段，1：申请
            RecKjPaperManagementD recordArchivesOld = recKjPaperManagementDMapper.selectRecKjPaperManagementDById(id);
            if ("0".equals(recordArchivesOld.getObjStr1()) || "3".equals(recordArchivesOld.getObjStr1())) { // 未申请或拒绝状态，可申请
                int res = this.updateRecKjPaperManagementD(recordArchives);
                if (res != 1) { // 更新条数为0
                    //手工回滚异常
                    TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
                    throw new ServiceException("操作失败！数据更新条数为0");
                }
            } else {
                //手工回滚异常
                TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
                throw new ServiceException("只允许操作未申请和审批拒绝的案卷");
            }
        }
        return 1;
    }

    @Override
    @Transactional
    public int updateArchivesApprove(String[] ids) {
        // 设置回滚点
        Object savePoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint();
        for (String id : ids) {
            RecKjPaperManagementD recordArchives = new RecKjPaperManagementD();
            recordArchives.setId(id);
            recordArchives.setObjStr1("2"); //申请状态字段,2：通过
            RecKjPaperManagementD recordArchivesOld = this.selectRecKjPaperManagementDById(id);
            // 如果总登记号为0，自增+1
//            if(recordArchivesOld.getRegistNum() == 0){
//                List<RecordArchives> archList = recordArchivesMapper.selectRegistNumCount();
//                if(archList.size() != 0){
//                    recordArchives.setRegistNum(archList.get(0).getRegistNum() + 1);
//                }else {
//                    recordArchives.setRegistNum(1); // 第一次添加
//                }
//            }
            if ("1".equals(recordArchivesOld.getObjStr1())) { // 申请中状态，可审批
                int res = this.updateRecKjPaperManagementD(recordArchives);
                if (res != 1) { // 更新条数为0
                    //手工回滚异常
                    TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
                    throw new ServiceException("操作失败！数据更新条数为0");
                }
            } else {
                //手工回滚异常
                TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
                throw new ServiceException("只允许操作申请中的案卷");
            }
        }
        return 1;
    }

    @Override
    @Transactional
    public int updateArchivesReject(String[] ids) {
        // 设置回滚点
        Object savePoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint();
        for (String id : ids) {
            RecKjPaperManagementD recordArchives = new RecKjPaperManagementD();
            recordArchives.setId(id);
            recordArchives.setObjStr1("3"); //申请状态字段，3：拒绝
            RecKjPaperManagementD recordArchivesOld = this.selectRecKjPaperManagementDById(id);
            // 如果总登记号为0，自增+1
//            if(recordArchivesOld.getRegistNum() == 0){
//                List<RecordArchives> archList = recordArchivesMapper.selectRegistNumCount();
//                if(archList.size() != 0){
//                    recordArchives.setRegistNum(archList.get(0).getRegistNum() + 1);
//                }else {
//                    recordArchives.setRegistNum(1); // 第一次添加
//                }
//            }
            if ("1".equals(recordArchivesOld.getObjStr1())) { // 申请中状态，可审批
                int res = this.updateRecKjPaperManagementD(recordArchives);
                if (res != 1) { // 更新条数为0
                    //手工回滚异常
                    TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
                    throw new ServiceException("操作失败！数据更新条数为0");
                }
            } else {
                //手工回滚异常
                TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
                throw new ServiceException("只允许操作申请中的案卷");
            }
        }
        return 1;
    }

}
